package com.mobilottery.ui;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;

import com.mobilottery.server.PersistenceManager;


/**
 * Helper class to handle session close on web request completion. 
 * The filter will close any outstanding persistence session that was opened during performing request.
 * The filter must be defined in the web.xml of web application.  
 * @author fedor
 */
public class PersistenceCloseFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if(PersistenceManager.isInstanceInitialized())
		{
			Logger.getLogger(getClass()).warn("closing orphan persistence manager instance");
			PersistenceManager.closeInstance();
		}
		chain.doFilter (request, response);
		if(PersistenceManager.isInstanceInitialized())
			PersistenceManager.closeInstance();
	}

	public void init(FilterConfig config) throws ServletException {
	}
}
